package com.fs.base.utils;

import java.net.URLEncoder;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;

/**
 * <p>Created by Raofeicheng on 2017/12/6.</p>
 * @author Raofeicheng
 * @version 1.0
 */
public class CommonUtils {

	/**
	 * 获取下载文件中文件的名称
	 */
	public static String encodeFilename(String filename, HttpServletRequest request) {
		/**
		 * 获取客户端浏览器和操作系统信息
		 * 在IE浏览器中得到的是：User-Agent=Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; Maxthon; Alexa Toolbar)
		 * 在Firefox中得到的是：User-Agent=Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.7.10) Gecko/20050717 Firefox/1.0.6
		 */
		String agent = StringUtils.trimToEmpty(request.getHeader("USER-AGENT")).toUpperCase();
		try {
			if (agent.contains("MSIE") || agent.contains("TRIDENT") || agent.contains("EDGE")) {
				String newFileName = URLEncoder.encode(filename, "utf-8");
				newFileName = newFileName.replace("+", "%20");    //IE下载文件名空格变+号问题
				return newFileName;
			} else return new String(filename.getBytes(), "ISO8859-1");
		} catch (Exception ex) {
			return filename;
		}
	}

	/**
	 * 获取byte长度
	 */
	public static int getByteLength(String str) {
		return null != str && 0 < str.length() ? str.getBytes().length : 0;
	}

}
